package com.fingard.dsp.bank.directbank.zjrc01;

import java.io.*;
import java.net.URLEncoder;
import java.util.*;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.DirectBase;
import com.fingard.net.WebRequest;
import com.fingard.text.StringHelper;
import com.fingard.util.TransIDHelper;
import com.fingard.xml.XmlTextWriter;
import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfReader;


public class ZJRC01Base extends DirectBase {

    protected String tranCode = "";
    protected String serialNo = "";
    protected String sign = "";//还不知道sign如何获取
    protected static final String banks="7047";
    protected static final String fontFamily="C:\\Windows\\Fonts\\simsun.ttc";//回单html转pdf中文字体
    protected static final String htmlCSS="<style type=\"css/text\">body{font-family:SimSun;}</style>";

    protected static TransIDHelper idHelper=new TransIDHelper(1,999);

    /**
     * 编码
     * @return
     */
    protected String getCharset(){
        return getBankConfig().getCharset("UTF-8");
    }

    protected void writeCommonHeader(XmlTextWriter xmlWriter) throws Exception {

        if (StringHelper.isNullOrEmpty(tranCode)) {
            throw new Exception("tranCode");
        }
        xmlWriter.writeStartDocByDeclaration("<?xml version=\"1.0\" encoding=\""+getCharset()+"\"?>");
        xmlWriter.writeStartElement("ebank");
        xmlWriter.writeStartElement("reqHead");
        xmlWriter.writeElementString("custNo",bankFront.loginName);
        xmlWriter.writeElementString("userId",bankFront.org);
        xmlWriter.writeElementString("tranCode",tranCode);
        xmlWriter.writeElementString("serialNo",serialNo);
        xmlWriter.writeElementString("reqDate", Format.Date8Format.format(new Date()));
        xmlWriter.writeElementString("reqTime", Format.Time9Format.format(new Date()));
        xmlWriter.writeEndElement();
        xmlWriter.writeStartElement("reqBody");
    }
    protected String[] sendToBank(String p_reqStr) throws Exception {

        String[] retStr = new String[]{"", ""};
        String httpUrl = "";
        int index = p_reqStr.indexOf("<ebank>");
        String p_head = p_reqStr.substring(0,index).replace("\r\n", "");
        String p_data = p_reqStr.substring(index).replace("\r\n","").replace(" ","");
        String p_reqString = p_head+p_data;
        //不知道需不需要转码
        String encodeString = URLEncoder.encode(p_reqString,getCharset());
        httpUrl = bankFront.serverURL;
        String httpUrl1 = "http://"+bankFront.serverIP+":"+bankFront.signPort+"/bce/yq.do";
        if("100024".equals(tranCode) || "100025".equals(tranCode)){
            httpUrl1 ="http://"+bankFront.serverIP+":"+bankFront.signPort;
        }
        //和银行文档上的方式不一样 没有sign数据 这边不知道上传那个数据
        String sendData = "tranCode="+tranCode+"&transData="+encodeString;
        if("100024".equals(tranCode)){
            sendData+="&url="+bankFront.getStrValueByFor("serverURL","100024");
        }else {
            sendData+="&url="+httpUrl;
        }
        WriteBankLogLn("2.提交银行的地址：" + httpUrl1);
        WriteBankLogStep2(p_reqString);
        //发送银行前置
        WebRequest tmpRequest = new WebRequest(httpUrl1);
        String charsetName = getCharset();
        byte[] tmpWriteBytes = sendData.getBytes(charsetName);
        retStr = tmpRequest.upload(tmpWriteBytes, charsetName);
        WriteBankLogStep3(retStr[1]);
        return retStr;
    }
    protected static boolean isActiveRetCode(String retCode) {
        if (retCode != null) {
            if (retCode.equals("0000")) {
                return true;
            }
        }
        return false;
    }

    /**
     * 列举银行所有{回单类型,业务类型}组合，因为银行不支持查询全部
     * @return
     */
    protected List<String[]> getAllReceiptType(){
        List<String[]> list=new ArrayList<String[]>();
        try {
            for(int i=0;i<6;i++){
                String key="0"+(i+1);
                String content=getBankConfig().getMapValueByKey("receiptTypeMapping",key);
                if(StringHelper.hasAnyChar(content)){
                    String[] valueArr=content.split(",");
                    for(String value:valueArr){
                        list.add(new String[]{key,value});
                    }
                }
            }
        } catch (Exception e) {
            WriteBankLogLn("回单类型配置有误，查询所有回单");
        }
        if(list==null || list.size()==0){
            String[][] receiptTypeAryAll=new String[][]{{"01","01"},{"01","02"},{"01","03"},{"01","04"},{"01","05"},{"01","06"},{"01","07"},
                 {"02","01"},{"03","01"},{"03","02"},{"04","01"},{"05","01"},{"06","01"},{"06","02"},{"06","03"}};
            list=Arrays.asList(receiptTypeAryAll);
        }
        return list;
    }

    protected String getQryTransID() {
        return Format.DateTime12Year2Format.format(new Date())+idHelper.getNextIDStr();
    }

    /**
     * 根据关键字截取值
     * @param context
     * @param key
     * @return
     */
    protected static String getValueByKey(String context,String key){
        int start=context.indexOf(">",context.indexOf("<td",context.indexOf(key)))+1;
        int end=context.indexOf("<",start);
        return context.substring(start,end);
    }

    /**
     * 根据关键字截取图标url
     * @param context
     * @param key
     * @return
     */
    protected String getImgUrlByKey(String context,String key){
        int start=context.indexOf("\"",context.indexOf("src",context.indexOf("<img",context.indexOf(key))))+1;
        int end=context.indexOf("\"",start);
        return context.substring(start,end);
    }

    /**
     * 校验pdf文件是否可以打开
     * @param file
     * @return
     */
    protected boolean isCheckPdf(String file){
        boolean flag=false;
        Document document=null;
        try {
            document = new Document(new PdfReader(file).getPageSize(1));
            document.open();
            PdfReader reader = new PdfReader(file);
            int n = reader.getNumberOfPages();
            if (n != 0)
                flag = true;
            //document.close();
        } catch (IOException e) {
            WriteBankLogLn("校验pdf文件异常："+e.getMessage());
        } finally {
            if(document!=null){
                document.close();
            }
        }
        return flag;
    }

    /**
     * 获取配置的间隔时间
     * @param code
     * @return
     */
    protected long sleepTime(String code){
        int time=Integer.parseInt(getBankConfig().getSetValue("sleepTime","0",code));
        return time*1000;
    }

    /**
     * 获取及调整html内容
     * @param htmlContext
     * @return
     */
    protected String getHtmlContent(String htmlContext){
        String charset=getCharset();
        BufferedReader reader=null;
        try {
            InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream(htmlContext.getBytes(charset)),charset);
            reader = new BufferedReader(isr);
            String readLine = "";
            Map<String,String> map=new HashMap<String, String>();
            //按行进行获取数据进行处理
            while ((readLine=reader.readLine())!=null) {
                String flag="<span>";
                if(readLine.indexOf(flag)<0){
                    flag="<span >";//兼容
                }
                int start=readLine.indexOf(flag);
                int end=readLine.indexOf("</span");
                if(start>-1){//处理所有<span></span>标签的内容
                    String key=readLine.substring(start+flag.length(),end);//原内容
                    String keyContent=readLine.substring(start+flag.length(),end);//待替换的内容
                    int checkLength=45;//限制长度为30时换行
                    //只处理长度超过限制长度的span内容
                    if(StringHelper.hasAnyChar(keyContent) && keyContent.getBytes(charset).length>checkLength){
                        StringBuilder value=new StringBuilder();
                        //开始处理内容，每过30个字节的长度就换行，30个字节等于10个中文字
                        while (keyContent.getBytes(charset).length>checkLength){
                            byte[] payNames=new byte[checkLength];
                            System.arraycopy(keyContent.getBytes(charset), 0, payNames, 0, checkLength);
                            String value1=new String(payNames,charset);
                            if(value1.substring(value1.length()-1).getBytes(charset)[0]<0){
                                value1=value1.substring(0,value1.length()-1);
                            }
                            keyContent=keyContent.substring(keyContent.indexOf(value1)+value1.length());
                            value.append(value1).append("<br/>");//插入换行符
                        }
                        value.append(keyContent);
                        if(StringHelper.hasAnyChar(key) && StringHelper.hasAnyChar(value.toString())){
                            map.put(key,value.toString());
                        }
                    }
                }
            }
            //将所有进行处理的内容与原内容进行替换
            for (Map.Entry<String,String> entry:map.entrySet()){
                htmlContext=htmlContext.replace(entry.getKey(),entry.getValue());
            }
        }catch (Exception e){
            if(reader!=null){
                try {
                    reader.close();
                }catch (Exception ex){
                    ex.printStackTrace();
                }
            }
        }
        return htmlContext;
    }
}
